package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.service.BankInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/6/6 17:09
 * @description :
 */
@Service
public class BankInfoServiceImpl implements BankInfoService {
    @Resource
    private EntityManager entityManager;

    @Override
    public List<String> getBankNameList() {
        StringBuilder sb = new StringBuilder("SELECT bank_name from banks GROUP BY bank_name");
        Query nativeQuery = entityManager.createNativeQuery(sb.toString());
        List<String> resultList = nativeQuery.getResultList();
        return resultList;
    }

    @Override
    public List<String> getForkBankNameList(Pageable pageable, String keyword, String province, String city, String bankName) {
        if(StringUtils.isBlank(province) || StringUtils.isBlank(city) || StringUtils.isBlank(bankName)){
            throw new BusinessException(Code.ERROR);
        }
        StringBuilder sb = new StringBuilder("select sub_branch_name from banks where province = :province and city = :city and bank_name=:bankName");
        if(StringUtils.isNotBlank(keyword)){
            sb.append(" and sub_branch_name like :keyword");
        }

        sb.append( " limit :start,:end");
        Query nativeQuery = entityManager.createNativeQuery(sb.toString());
        nativeQuery.setParameter("province",province);
        nativeQuery.setParameter("city",city);
        nativeQuery.setParameter("bankName",bankName);
        if(StringUtils.isNotBlank(keyword)){
            nativeQuery.setParameter("keyword",keyword);
        }
        nativeQuery.setParameter("start",pageable.getPageNumber());
        nativeQuery.setParameter("end",pageable.getPageSize());
        return  nativeQuery.getResultList();
    }
}
